<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller;

use App\Service\LoginService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Swagger\Annotation as SA;
use Hyperf\Swagger\Request\SwaggerRequest;

#[SA\HyperfServer('http')]
class LoginController extends Controller
{
    #[Inject]
    protected LoginService $loginService;

    #[SA\Post(path: '/login', summary: '客户端登录', tags: ['登录注册接口'])]
    #[SA\RequestBody(content: new SA\JsonContent(properties: [
        new SA\Property(property: 'username', description: '用户名', type: 'string', rules: 'required|string'),
        new SA\Property(property: 'password', description: '密码', type: 'string', rules: 'required|string'),
    ]))]
    #[SA\Response(response: '200', content: new SA\JsonContent(ref: '#/components/schemas/LoginSchema'))]
    public function login(SwaggerRequest $request)
    {
        $username = (string) $request->post('username');
        $password = (string) $request->post('password');

        if (! $username || ! $password) {
            return $this->response->fail(-1, '登录失败，用户名和密码不能为空');
        }

        $result = $this->loginService->login($username, $password);
        var_dump($result);
        return $this->response->success($result);
    }

    #[SA\Post(path: '/register', summary: '客户端注册', tags: ['登录注册接口'])]
    #[SA\RequestBody(content: new SA\JsonContent(properties: [
        new SA\Property(property: 'username', description: '用户名', type: 'string', rules: 'required|string'),
        new SA\Property(property: 'password', description: '密码', type: 'string', rules: 'required|string'),
    ]))]
    #[SA\Response(response: '200', content: new SA\JsonContent(ref: '#/components/schemas/UserSchema'))]
    public function register(SwaggerRequest $request)
    {
        $username = (string) $request->post('username');
        $password = (string) $request->post('password');

        if (! $username || ! $password) {
            return $this->response->fail(-1, '注册失败，用户名和密码不能为空');
        }

        $user = $this->loginService->register($username, $password);
        if ($user->id) {
            return $this->response->success($user);
        }
        return $this->response->fail(-1, '注册失败，请重试');
    }
}
